# -*- coding: utf-8 -*-
"""
@Time ： 2021/1/20 15:39
@Auth ： 张张呀
@File ：taobao.py
@IDE ：PyCharm
@Motto：ABC(Always Be Coding)

"""
import time

from selenium import webdriver


class Taobao:
    def __init__(self):
        self.url = 'http://www.taobao.com'

    def search_product(self, keyword, driver):
        driver.find_element_by_id('q').send_keys(keyword)
        time.sleep(2)
        driver.find_element_by_class_name('btn-search').click()

        time.sleep(2)

        driver.find_element_by_css_selector('.iconfont.icon-qrcode').click()

        # driver.find_element_by_css_selector('[type=submit]').click()
        time.sleep(10)

    def drop_down(self, driver):
        for x in range(1, 11, 2):
            time.sleep(0.5)
            j = x / 10
            js = 'document.documentElement.scrollTop = document.documentElement.scrollHeight * %f' % j
            driver.execute_script(js)

    def get_product(self, driver):
        lis = driver.find_elements_by_xpath('//div[@class="items"]/div[@class="item J_MouserOnverReq  "]')
        print(lis)
        for li in lis:
            info = li.find_element_by_xpath('.//div[@class="row row-2 title"]').text
            price = li.find_element_by_xpath('.//a[@class="J_ClickStat"]').get_attribute('trace-price')
            deal = li.find_element_by_xpath('.//div[@class="deal-cnt"]').text
            image = li.find_element_by_xpath('.//div[@class="pic"]/a/img').get_attribute('src')
            name = li.find_element_by_xpath('.//div[@class="shop"]/a/span[2]').text
            position = li.find_element_by_xpath('.//div[@class="row row-3 g-clearfix"]/div[@class="location"]').text
            print(info + '|' + price + '|' + deal + '|' + name + '|' + image + '|' + position)

    def run(self):
        keyword = input('关键字:')
        driver = webdriver.Chrome()
        driver.get(self.url)
        self.search_product(keyword, driver)
        self.drop_down(driver)
        self.get_product(driver)
        for num in range(1, 10):
            driver.get('https://s.taobao.com/search?q={}&s={}'.format(keyword, 44 * num))
            driver.implicitly_wait(10)
            self.drop_down(driver)
            self.get_product(driver)


if __name__ == '__main__':
    Taobao().run()
